import jwt from '@/utils/jwt.js';
import {timSigGen} from '@/common/http.api.js'
const app = getApp();

export  function timLogin() {
	let userId = jwt.getUserId();
	let that = this;
	app.$store.commit("toggleIsSDKReady", false);
	app.globalData.userId = userId;
	//app.globalData.userInfo.id = userID;
	const authToken = jwt.getAccessToken();
	timSigGen({params:{userId:userId},header: {'Authorization': authToken ? `Bearer ${authToken}` : ''}}).then(resone => {
		if (resone.code === 0) {
			debugger
			// const userSig = resone.data.sig;
			// const avatar = resone.data.avatar;
			// const nickname = resone.data.nickname;
			// const SDKAppID = resone.data.appId;
			app.globalData.userSig = resone.data.sig;
			app.globalData.avatar = resone.data.avatar;
			app.globalData.nickname = resone.data.nickname;
			app.globalData.SDKAppID = resone.data.appId;
			uni.$TUIKit.login({
				userID: userId + '',
				userSig: app.globalData.userSig
			}).then((restwo) => {
				if (restwo.data.repeatLogin === true) {
					// 标识账号已登录，本次登录操作为重复登录。v2.5.1 起支持
					console.log(restwo.data.errorInfo);
					uni.$TUIKit.logout().then((resthree) => {
							if (resthree.code === 0) {
								//uni.clearStorage();
								//app.globalData.resetLoginData();
							}
					});
				}else{
					//登录成功后 更新登录状态
					this.$store.commit("toggleIsLogin", true);
					this.$store.commit("setTimUserInfo",restwo.data)
					
					//tim 返回的用户信息
					//uni.setStorageSync('userTIMInfo', JSON.stringify(res.data))
					uni.$aegis.reportEvent({
						name: 'login',
						ext1: 'login-success',
						ext2: 'uniTuikitExternal',
						ext3: `${app.globalData.SDKAppID}`,
					})
				}
			}).catch((error) => {
				uni.$aegis.reportEvent({
					name: 'login',
					ext1: `login-failed#error:${error}`,
					ext2: 'uniTuikitExternal',
					ext3: `${app.globalData.SDKAppID}`,
				})
			})
		} else {
			uni.hideLoading();
			this.$refs.uToast.show({
				message: resone.msg,
				type: 'error',
			})
		}
	});
}